//
//  MSLoginManager.m
//  MSJD
//
//  Created by 箭军刘 on 2018/11/2.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSLoginManager.h"

#import "MSLoginDataSource.h"
#import "WXApi.h"

@interface MSLoginManager()

@property (nonatomic, weak) UIViewController *currentVC;

@property (nonatomic, readwrite, assign) NSInteger type;

@end

@implementation MSLoginManager

+ (instancetype)loadLoginManagerWithCurrentVC:(UIViewController *)currentVC {
    MSLoginManager *loginManager = [[MSLoginManager alloc] init];
    loginManager.currentVC = currentVC;
    return loginManager;
}

#pragma mark - Init Method

/** 初始化微信登录通知 */
- (void)initWechatLoginNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveWechatLoginStatusNty:) name:@"wechatDidLoginNotification" object:nil];
}
/** 移除微信登录通知 */
- (void)removeWechatLoginNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatDidLoginNotification" object:nil];
}

#pragma mark - Notifications

/** 收到微信登录状态通知 */
- (void)receiveWechatLoginStatusNty:(NSNotification *)notification {
    
    [self removeWechatLoginNotification];
    
    NSDictionary *userInfo = notification.userInfo;
    if (!userInfo[@"errcode"]) {
        return;
    }
    NSInteger errCode = [userInfo[@"errcode"] integerValue];
    if (errCode == 0) {
        // 授权成功，查询微信账号信息
        if (![MSSafeObject isNull:userInfo[@"code"]]) {
            [self wechatAuthorSuccess:[MSSafeObject stringInfo:userInfo[@"code"]]];
            return;
        }
    }
    // 授权不成功，提示用户
    NSString *errorMsg = @"";
    if (errCode == -2) {
        errorMsg = @"您已选择了取消授权";
    } else if (errCode == -3) {
        errorMsg = @"授权信息发送失败";
    } else if (errCode == -5) {
        errorMsg = @"当前微信不支持登录";
    } else {
        errorMsg = @"授权失败，请稍后重试";
    }
    [self invokeFailedMessageWithType:1 errorMsg:errorMsg];
}

#pragma mark - Public Method

- (void)phoneLoginWithPhone:(NSString *)phone pwd:(NSString *)pwd {
    
    // 提示
    [MBProgressHUD showMessage:@"登录中"];
    _WEAKSELF
    [MSLoginDataSource loginWithPhone:phone pwd:pwd success:^(NSDictionary * _Nonnull responseInfo) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showDefaultHUDWithText:@"登录成功" toView:weakSelf.currentVC.view];
        [weakSelf loginSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        NSString *errorMsg = error.localizedDescription?:@"登录失败";
        [weakSelf invokeFailedMessageWithType:0 errorMsg:errorMsg];
    }];
}

- (void)wechatLogin {
    if (![WXApi isWXAppInstalled]) {
        [self invokeFailedMessageWithType:1 errorMsg:@"未安装微信，请安装之后再重试"];
        return;
    }
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    // 第三方向微信终端发送一个SendAuthReq消息结构
    if ([WXApi sendReq:req]) {
        [self initWechatLoginNotification];
    }
}

#pragma mark - Private Method

/** 微信授权成功 */
- (void)wechatAuthorSuccess:(NSString *)code {
    
    [MBProgressHUD showMessage:@"登录中..."];
    _WEAKSELF
    [MSLoginDataSource queryWechatAccountInfoAndOpenIdWithCode:code success:^(NSDictionary * _Nonnull responseInfo) {
        [weakSelf loginWechatAccountInfo:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        NSString *errorMsg = error.localizedDescription?:@"获取账号信息失败";
        [weakSelf invokeFailedMessageWithType:1 errorMsg:errorMsg];
    }];
}
/** 登录微信账号（自己的服务器登录调用） */
- (void)loginWechatAccountInfo:(NSDictionary *)response {
    
    NSString *avatar = [MSSafeObject stringInfo:response[@"headimgurl"]];
    NSInteger gender = response[@"sex"]?[response[@"sex"] integerValue]:0;
    NSString *openId = [MSSafeObject stringInfo:response[@"openid"]];
    NSString *nickName = [MSSafeObject stringInfo:response[@"nickname"]];
    _WEAKSELF
    [MSLoginDataSource wechatLoginWithPhone:@"" avatar:avatar gender:gender openId:openId nickname:nickName success:^(NSDictionary * _Nonnull responseInfo) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showDefaultHUDWithText:@"登录成功" toView:weakSelf.currentVC.view];
        [weakSelf loginSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        NSString *errorMsg = error.localizedDescription?:@"登录失败";
        [weakSelf invokeFailedMessageWithType:1 errorMsg:errorMsg];
    }];
}
/** 登录成功 */
- (void)loginSuccess:(NSDictionary *)response {
    // 本地账号数据存储
    /*
     {
     avatar = "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIThibpemosFlBEu3iaL3IEKp6CSb6E2uoKNo0r756GCeCmAzzSK2Sd0KGG5jJ1lIEYaMQyAUVmPdAg/132";
     gender = 1;
     id = 4;
     password = "";
     phone = "";
     token = 7859026435b7454abbef;
     username = "\U5218\U7bad\U519b";
     uuid = 7859026435b7454abbef35225c7d01a0;
     }
     */
    MSUser *loginUser = [MSUser modelWithJSON:response];
//    MSUser *loginUser = [[MSUser alloc] initWithLoginResponse:response];
    [UserAccesser saveAccountToLocal:loginUser];
    
    if (self.LoginSuccessBlock) {
        self.LoginSuccessBlock(1);
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:MSUserLoginSuccessNotification object:nil];
}

/** 调用失败消息 */
- (void)invokeFailedMessageWithType:(NSInteger)type errorMsg:(NSString *)errorMsg {
    [MBProgressHUD hideHUD];
    if (![MSSafeObject isNull:errorMsg]) {
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:self.currentVC.view];
    }

    if (self.LoginFailedBlock) {
        self.LoginFailedBlock(type);
    }
}

#pragma mark -  Memory Method
- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
